import React, { Component } from 'react'
import { nanoid } from 'nanoid'
import { connect } from 'react-redux'
import { createAddPersonAction } from '../../redux/actions/person'

class Person extends Component {
  nameRef = React.createRef()
  ageRef = React.createRef()

  addPerson = () => {
    const name = this.nameRef.current.value
    const age = this.ageRef.current.value
    const personObj = { id: nanoid(), name, age }
    this.props.jia(personObj)
    this.nameRef.current.value = ''
    this.ageRef.current.value = ''
  }

  render() {
    const { count, personData } = this.props
    return (
      <div>
        <h2>我是人数列表组件，当前 count 和为 {count}</h2>
        <div>
          <input ref={this.nameRef} type="text" placeholder="请输入姓名" />
          <input ref={this.ageRef} type="text" placeholder="请输入年龄" />
          <button onClick={this.addPerson}>添加</button>
        </div>
        <ul>
          {personData.map((item) => {
            return (
              <li key={item.id}>
                姓名：{item.name}，年龄：{item.age}
              </li>
            )
          })}
        </ul>
      </div>
    )
  }
}

export default connect(
  // 映射操作状态
  ({ personData, he: count }) => ({ personData, count }),
  // 映射操作状态的方法，简写形式直接把 action 引入
  {
    jia: createAddPersonAction
  }
)(Person)
